package com.example.demo.forkjoin;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.ForkJoinTask;

public class MyForkJoinTask extends ForkJoinTask<Void> {
    /*
        Returns the result that would be returned by {@link #join}, even
        if this task completed abnormally, or {@code null} if this task
        is not known to have been completed.  This method is designed
        to aid debugging, as well as to support extensions. Its use in
        any other context is discouraged.

        @return the result, or {@code null} if not completed
     */
    @Override
    public Void getRawResult() {
        return null;
    }


    /*
       Forces the given value to be returned as a result.  This method
       is designed to support extensions, and should not in general be
       called otherwise.

       @param value the value
     */
    @Override
    protected void setRawResult(Void value) {

    }

    /*
       Immediately performs the base action of this task and returns
       true if, upon return from this method, this task is guaranteed
       to have completed normally. This method may return false
       otherwise, to indicate that this task is not necessarily
       complete (or is not known to be complete), for example in
       asynchronous actions that require explicit invocations of
       completion methods. This method may also throw an (unchecked)
       exception to indicate abnormal exit. This method is designed to
       support extensions, and should not in general be called
       otherwise.

       立即执行此任务的基本操作，如果从该方法返回后，保证此任务已正常完成，则返回true。
       否则，此方法可能返回false，以表示该任务不一定要完成（或不知道是完成的），
       例如在需要显式调用完成方法的异步操作中。此方法还可能引发（未经检查的）异常以指示异常退出。
       此方法旨在支持扩展，通常不应以其他方式调用。

       @return {@code true} if this task is known to have completed normally
     */
    @Override
    protected boolean exec() {
        return false;
    }



    public static void main(String[] args) throws Exception {
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        Unsafe unsafe = (Unsafe) f.get(null);

        A o1 = new A(); // constructor
        o1.a(); // prints 1
        A o2 = A.class.newInstance(); // reflection
        o2.a(); // prints 1
        A o3 = (A) unsafe.allocateInstance(A.class); // unsafe
        o3.a(); // prints 0
    }

    static class A {
        private long a; // not initialized value, default 0
        public A() {
            this.a = 1; // initialization
        }
        public long a() {
            return this.a;
        }
    }

}
